//
//  SEHomeController.m
//  kuaiyi
//
//  Created by Alphts on 16/7/5.
//  Copyright © 2016年 Alphts. All rights reserved.

#import "SEHomeController.h"
#import "SEHomeKindView.h"
#import "SEWeatherDTO.h"
#import "SEProvineController.h"
#import "SEMedicalRecordInfo.h"
#import "SEWebViewController.h"
#import "LWLoopCell.h"
#import "LWLoopView.h"
#import <CoreLocation/CoreLocation.h>

#define kScreenWidth [UIScreen mainScreen].bounds.size.width

#define kHeaderTextColor [UIColor colorWithRed:58/256.0 green:198/256.0 blue:198/256.0 alpha:1.0]

@interface SEHomeController ()<LWLoopViewDelegate,CLLocationManagerDelegate>

//位置管理器
@property (nonatomic, strong) CLLocationManager *locationManager;
//地理编码
@property (nonatomic, strong) CLGeocoder *geocoder;

@property (nonatomic, copy) NSString *currentLocality;


@property (nonatomic, weak) LWLoopView *loopView;


@property(nonatomic,strong) NSTimer *timer;

@property (nonatomic, weak) UIView *bottomView;

//button图片数组
@property (nonatomic, strong) NSArray *btnImgStrArray;
//button标题数组
@property (nonatomic, strong) NSArray *btnTitleArray;
//底部按钮数组
@property (nonatomic, strong) NSMutableArray *bottomArray;
//轮播器的图片url字符串数组
@property (nonatomic, strong) NSArray * looperURLDataArray;

//天气imgView
@property (nonatomic, weak) UIImageView *iv_weather;
//天气label
@property (nonatomic, weak) UILabel *lb_weather;
//地点label
@property (nonatomic, weak) UILabel *lb_place;
//温度label
@property (nonatomic, weak) UILabel *lb_temperature;
//日期label
@property (nonatomic, weak) UILabel *lb_data;


@end

@implementation SEHomeController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.btnImgStrArray = @[@"zl",@"xyg",@"sj",@"xy",@"gt",@"gy"];
    self.btnTitleArray = @[@"肿瘤",@"心血管",@"神经科",@"血液科",@"骨科",@"公益"];
    
    [self setupUI];
    
    [self initWeatherInfo];
    
    [self startLocation];
    
    
}



#pragma mark - ViewDidLayoutSubviews
- (void)viewDidLayoutSubviews{
    [super viewDidLayoutSubviews];
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        
        NSInteger row = 2;
        NSInteger column = 3;
        CGFloat margin = 2;
        CGFloat width = (_bottomView.w - (column-1)*margin)/column;
        CGFloat height = (_bottomView.h -row*margin)/row;
        for (int i = 0; i < self.btnImgStrArray.count; i++) {
            NSInteger colIndex = i % column;
            NSInteger rowIndex = i / column;
            CGFloat viewX = colIndex * (width + margin);
            CGFloat viewY = rowIndex * height + (rowIndex + 1)*margin;
            
            SEHomeKindView *view = self.bottomArray[i];
            
            view.frame = CGRectMake(viewX, viewY, width, height);
            
            view.imgName = self.btnImgStrArray[i];
            view.title = self.btnTitleArray[i];
            view.index = i;
        }
        
    });
}


#pragma mark - 初始化界面
//设置UI界面
- (void)setupUI{
    
    self.navigationController.navigationBar.barTintColor = kThemeColor;
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.title = @"马医一生";
    
    //MARK: 1.创建控件
    //1.头部天气和日期view
    UIView *headerView = [[UIView alloc] init];
    headerView.backgroundColor = [UIColor colorWithRed:170/256.0 green:240/256.0 blue:220/256.0 alpha:1.0];
    [self.view addSubview:headerView];
    
    UIImageView *iv_weather = [[UIImageView alloc] init];
    self.iv_weather = iv_weather;
    [headerView addSubview:iv_weather];
    
    //1.1天气label
    UILabel *lb_weather = [[UILabel alloc] init];
    self.lb_weather = lb_weather;
    lb_weather.text = @"大雨";
    lb_weather.numberOfLines = 2;
    
    if (kDevice_Is_iPhone5) {
        lb_weather.font =FONT(12);
    }else if (kDevice_Is_iPhone6){
        lb_weather.font =FONT(14);
    }else{
        lb_weather.font =FONT(16);
    }
    
    lb_weather.textColor = kHeaderTextColor;
    [headerView addSubview:lb_weather];
    
    //1.2分割线
    UIImageView *iv_line = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"fengexian"]];
    [iv_line sizeToFit];
    [headerView addSubview:iv_line];
    
    //1.3地点
    UILabel *lb_place = [[UILabel alloc] init];
    self.lb_place = lb_place;
    UIFont *lb_placeFont;
    if (kDevice_Is_iPhone5) {
        lb_placeFont =FONT(12);
    }else if (kDevice_Is_iPhone6){
        lb_placeFont =FONT(14);
    }else{
        lb_placeFont =FONT(16);
    }
    NSAttributedString *lbStr = [[NSAttributedString alloc] initWithString:@"城市" attributes:@{NSForegroundColorAttributeName:kHeaderTextColor,NSUnderlineStyleAttributeName:@2,NSFontAttributeName:lb_placeFont}];
    lb_place.attributedText = lbStr;
    lb_place.userInteractionEnabled = YES;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(didClickPlace:)];
    [lb_place addGestureRecognizer:tap];
    [headerView addSubview:lb_place];
    
    //1.4温度
    UILabel *lb_temperature = [[UILabel alloc] init];
    self.lb_temperature = lb_temperature;
    lb_temperature.text = @"温度:";
    
    if (kDevice_Is_iPhone5) {
        lb_temperature.font =FONT(12);
    }else if (kDevice_Is_iPhone6){
        lb_temperature.font =FONT(14);
    }else{
        lb_temperature.font =FONT(16);
    }
    
    lb_temperature.textColor = kHeaderTextColor;
    lb_temperature.textAlignment = NSTextAlignmentCenter;
    [headerView addSubview:lb_temperature];
    
    //1.5日期
    UILabel *lb_data = [[UILabel alloc] init];
    self.lb_data = lb_data;
    lb_data.text = @"日期:";
    
    if (kDevice_Is_iPhone5) {
        lb_data.font =FONT(12);
    }else if (kDevice_Is_iPhone6){
        lb_data.font =FONT(14);
    }else{
        lb_data.font =FONT(16);
    }
    
    lb_data.textColor = kHeaderTextColor;
    lb_data.textAlignment = NSTextAlignmentCenter;
    [headerView addSubview:lb_data];
    
    
    //2.轮播的collectionView
    CGFloat height;
    if (kDevice_Is_iPhone5) {
        height = 170;
    }else if (kDevice_Is_iPhone6Plus){
        height = 240;
    }else{
        height = 210;
    }
    
    LWLoopView *loopView = [[LWLoopView alloc] initWithItemSize:CGSizeMake([UIScreen mainScreen].bounds.size.width, height) loopStyle:kLoopStylePage];
    self.loopView = loopView;
    loopView.pageColor = [UIColor blackColor];
    loopView.currentPageColor = [UIColor greenColor];
    loopView.autoLoop = YES;
    loopView.loopDelegate = self;
    
    [self.view addSubview:loopView];
    
    
    
    //3.名医通的view
    UIView *middleView = [[UIView alloc] init];
    [self.view addSubview:middleView];
    
    //3.1左侧的小view
    UIImageView *smallImgView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"yj"]];
    [middleView addSubview:smallImgView];
    
    //3.2名医通label
    UILabel *lb_doctor = [[UILabel alloc] init];
    lb_doctor.text = @"名医通";
    lb_doctor.font = FONT(20);
    [middleView addSubview:lb_doctor];
    
    //4.底部的九宫格view
    UIView *bottomView = [[UIView alloc] init];
    self.bottomView = bottomView;
    bottomView.backgroundColor = [UIColor grayColor];
    [self.view addSubview:bottomView];
    
    //创建九宫格View
    
    for (int i = 0; i < self.btnImgStrArray.count; i++) {
        SEHomeKindView *view = [[SEHomeKindView alloc] initWithFrame:CGRectZero];
        [_bottomView addSubview:view];
        
        //为View里的Button设置Tag(通过重写index属性的set方法)
        view.index = i;
        
        //点击按钮回调的block
        view.kindViewBlock = ^(NSInteger tag){
            
            [self didClickKindButtonWith:tag];
        };
        
        [self.bottomArray addObject:view];
    }
    
    //MARK: 2.设置约束
    //1.头部天气和日期view
    [headerView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.mas_equalTo(self.mas_topLayoutGuideBottom);
        
        make.trailing.leading.mas_equalTo(self.view);
        
        if (kDevice_Is_iPhone5) {
            make.height.mas_equalTo(60);
        }else if(kDevice_Is_iPhone6){
            make.height.mas_equalTo(70);
        }else{
            make.height.mas_equalTo(80);
        }
    }];
    
    [iv_weather makeConstraints:^(MASConstraintMaker *make) {
        
        make.centerY.equalTo(headerView);
        make.leading.equalTo(headerView).offset(10);
        if (kDevice_Is_iPhone5) {
            make.width.equalTo(45);
            make.height.equalTo(35);
        }else if(kDevice_Is_iPhone6){
            
            make.width.equalTo(55);
            make.height.equalTo(45);
        }else{
            make.width.equalTo(65);
            make.height.equalTo(55);
        }
    }];
    
    [lb_weather makeConstraints:^(MASConstraintMaker *make) {
        
        make.centerY.equalTo(headerView);
        
        make.leading.equalTo(iv_weather.trailing).offset(10);
        
        if (kDevice_Is_iPhone5) {
            make.width.equalTo(50);
        }else if(kDevice_Is_iPhone6){
            make.width.equalTo(60);
        }else{
            make.width.equalTo(70);
        }
        
        
    }];
    
    [iv_line makeConstraints:^(MASConstraintMaker *make) {
        
        make.center.equalTo(headerView);
        make.top.equalTo(headerView).offset(10);
        make.width.equalTo(3);
    }];
    
    [lb_place makeConstraints:^(MASConstraintMaker *make) {
        
        make.centerY.equalTo(headerView);
        make.trailing.equalTo(iv_line.leading).offset(-10);
    }];
    
    [lb_temperature makeConstraints:^(MASConstraintMaker *make) {
        
        make.leading.equalTo(iv_line.trailing);
        make.trailing.equalTo(headerView);
        make.top.equalTo(headerView);
        make.height.equalTo(35);
    }];
    
    [lb_data makeConstraints:^(MASConstraintMaker *make) {
        
        make.leading.equalTo(iv_line.trailing);
        make.trailing.equalTo(headerView);
        make.bottom.equalTo(headerView.bottom);
        make.height.equalTo(35);
    }];
    
    //2.轮播的collectionView
    [self.loopView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.mas_equalTo(headerView.mas_bottom);
        
        make.leading.trailing.mas_equalTo(self.view);
        
        
        if (kDevice_Is_iPhone5) {
            make.height.mas_equalTo(170);
        }else if (kDevice_Is_iPhone6Plus){
            make.height.mas_equalTo(240);
        }else{
            make.height.mas_equalTo(210);
        }
        
    }];
    
    //3.名医通的view
    [middleView makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.equalTo(loopView.bottom);
        make.trailing.leading.equalTo(self.view);
        make.height.equalTo(43);
    }];
    
    [smallImgView makeConstraints:^(MASConstraintMaker *make) {
        
        make.leading.equalTo(middleView).offset(10);
        make.centerY.equalTo(middleView);
    }];
    
    [lb_doctor makeConstraints:^(MASConstraintMaker *make) {
        
        make.leading.equalTo(smallImgView.trailing).offset(20);
        make.centerY.equalTo(smallImgView);
    }];
    
    //4.底部的九宫格view
    [bottomView makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.equalTo(middleView.bottom);
        make.bottom.leading.trailing.equalTo(self.view);
    }];

}

//初始化天气信息(默认上海)
- (void)initWeatherInfo{
    [SEWeatherDTO modelWithCityName:@"上海" successBlock:^(SEWeatherDTO *model) {
        
        [self setWeatherInfoWith:@"上海" weatherText:model.weather weatherPicURLStr:model.dayPictureUrl temperature:model.temperature date:model.trueData];
        
    } errorBlock:^{
        NSLog(@"error");
    }];
}


- (void)initLocalCity{
    [SEWeatherDTO modelWithCityName:[NSString stringWithFormat:@"%@",self.currentLocality] successBlock:^(SEWeatherDTO *model) {
        
        [self setWeatherInfoWith:self.currentLocality weatherText:model.weather weatherPicURLStr:model.dayPictureUrl temperature:model.temperature date:model.trueData];
        
    } errorBlock:^{
        NSLog(@"error");
    }];
}

-(void)startLocation{
    
    if ([CLLocationManager locationServicesEnabled]) {
        
        [self.locationManager startUpdatingLocation];
        
        //相隔多少米情况下定位一次
        self.locationManager.distanceFilter = 100;
        
        [self.locationManager requestAlwaysAuthorization];
        
    }else{
        
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"请检查您的网络或者是否开启定位功能" message:nil preferredStyle:UIAlertControllerStyleAlert];
        
        UIAlertAction *sureAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
        
        [alert addAction:sureAction];
        
        [self presentViewController:alert animated:YES completion:nil];
        
    }
    
}

-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations{
    //locations数组里边存放的是CLLocation对象，一个CLLocation对象就代表着一个位置
    CLLocation *loc = [locations firstObject];
    
    [self.geocoder reverseGeocodeLocation:loc completionHandler:^(NSArray *placemarks, NSError *error) {
        
        if (error||placemarks.count==0) {
            
            NSLog(@"loacation error");
            
        }else{
            CLPlacemark *firstPlacemark=[placemarks firstObject];
            
            
            self.currentLocality = firstPlacemark.locality;
            
            NSInteger cityNum = self.currentLocality.length -1;
            
            self.currentLocality = [self.currentLocality substringToIndex:cityNum];
            
        }
    }];
    
    //停止更新位置（如果定位服务不需要实时更新的话，那么应该停止位置的更新）
    [self.locationManager stopUpdatingLocation];
    
}



#pragma mark - 私有方法

#pragma mark - 九宫格按钮跳转逻辑

- (void)didClickKindButtonWith:(NSInteger)tag{
    
    if ([_btnTitleArray[tag] isEqualToString:@"公益"]) {
        
        SEWebViewController * con = [SEWebViewController new];
        con.view.backgroundColor = [UIColor whiteColor];
        con.title = @"公益";
        [self.navigationController pushViewController:con animated:YES];
        
    }else{
        
        SEMedicalRecordInfo * con = [SEMedicalRecordInfo new];
        con.view.backgroundColor = [UIColor colorWithRed:241/255.0 green:241/255.0 blue:246/255.0 alpha:1];
        con.title = _btnTitleArray[tag];
        con.mytitle = _btnTitleArray[tag];
        [self.navigationController pushViewController:con animated:YES];
        
    }
    
}

//天气信息代码封装
- (void)setWeatherInfoWith:(NSString *)place weatherText:(NSString *)weatherText weatherPicURLStr:(NSString *)weatherPicURLStr temperature:(NSString *)temperature date:(NSString *)date{
    
    self.lb_weather.text = weatherText;
    
    self.lb_place.attributedText = [[NSAttributedString alloc] initWithString:place attributes:@{NSForegroundColorAttributeName:kHeaderTextColor,NSUnderlineStyleAttributeName:@2,NSFontAttributeName:FONT(14)}];
    
    [self.iv_weather sd_setImageWithURL:[NSURL URLWithString:weatherPicURLStr]];
    
    self.lb_temperature.text = [NSString stringWithFormat:@"温度:%@",temperature];
    
    self.lb_data.text = [NSString stringWithFormat:@"日期:%@",date];
    
}


//点击地点label的手势
- (void)didClickPlace:(UITapGestureRecognizer *)tap{
    
    SEProvineController *provinceVc = [SEProvineController new];
    
    provinceVc.cityBlock = ^(SEWeatherDTO *model,NSString *cityName){
        
        //可以根据天气的早晚设置不同的imgview
        
        [self setWeatherInfoWith:cityName weatherText:model.weather weatherPicURLStr:model.dayPictureUrl temperature:model.temperature date:model.trueData];
        
    };
 
    [self.navigationController pushViewController:provinceVc animated:YES];
    
}

#pragma mark - 代理方法
- (NSArray<NSString *> *)photoURLStrWithLoopView:(LWLoopView *)loopView{
    
    return @[
             @"http://img.guahao.com/portal_upload/rollingnews/1453447883150.jpg",
             @"http://img.guahao.com/portal_upload/mediafocus/1461826474435.jpg",
             @"http://img.guahao.com/portal_upload/rollingnews/1461574027543.jpg"
             ];
}



#pragma mark - lazyload
- (NSMutableArray *)bottomArray{
    if (!_bottomArray) {
        _bottomArray = [NSMutableArray array];
    }
    return _bottomArray;
}


//懒加载位置管理器
-(CLLocationManager *)locationManager{
    
    if (!_locationManager) {
        
        self.locationManager = [[CLLocationManager alloc] init];
        
        self.locationManager.delegate = self;
    }
    return _locationManager;
}

//地理编码懒加载
-(CLGeocoder *)geocoder{
    if (!_geocoder) {
        
        _geocoder = [[CLGeocoder alloc] init];
    }
    return _geocoder;
}

//重写目前城市的set方法,只要赋值就刷新当前城市的天气信息
- (void)setCurrentLocality:(NSString *)currentLocality{
    _currentLocality = currentLocality;
    [self initLocalCity];
}



@end









